package com.lm.redisson.controller;

import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rw")
public class RWController {

    @Resource
    private RedissonClient redissonClient;

    private static final String KEY = "product:value";

    @GetMapping("/write")
    public String write() throws InterruptedException {
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("rw-lock");
        RLock lock = rwLock.writeLock();

        lock.lock();
        try {
            Thread.sleep(2000);
            redissonClient.getBucket(KEY).set("写入时间：" + System.currentTimeMillis());
            return "write ok";
        } finally {
            lock.unlock();
        }
    }

    @GetMapping("/read")
    public String read() {
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("rw-lock");
        RLock lock = rwLock.readLock();

        lock.lock();
        try {
            return (String) redissonClient.getBucket(KEY).get();
        } finally {
            lock.unlock();
        }
    }
}

